package com.woniuxy.controller;

import com.woniuxy.entity.IpLocationInfo;
import com.woniuxy.service.IpLocationService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/life/location")
public class IpLocationController {
    @Autowired
    private IpLocationService locationService;


    /**
     * 获取客户端IP地址和地理位置信息
     */
    @GetMapping("/getLocation")
    public ResponseEntity<?> getLocation(HttpServletRequest request,
                                         @RequestParam(required = false, name = "ip") String ip) {
        try {
            // 如果未提供IP参数，则使用客户端IP
            String targetIp = (ip != null && !ip.isEmpty()) ? ip : locationService.getClientIp(request);
            System.out.println("targetIp:"+targetIp);

            // 获取地理位置信息
            IpLocationInfo locationInfo = locationService.getLocationByIp(targetIp);

            // 返回成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", locationInfo);
            System.out.println("getLocation:"+result);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 返回错误响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取地理位置信息失败: " + e.getMessage());
            System.out.println("getLocation:"+result);
            return ResponseEntity.status(500).body(result);
        }
    }
}
